import { _decorator, CCFloat, Component, EventTouch, input, Input, math, Node, Sprite, v3, Vec3 } from 'cc';
import { VirtualInput } from '../input/VirtualInput';
const { ccclass, property } = _decorator;

@ccclass('Joystick')
export class Joystick extends Component {
    @property(Node)
    private stickBg: Node = null

    @property(Sprite)
    private thumbnail: Sprite = null

    @property({ type: CCFloat })
    private radius: number = 130

    private isFixed: boolean = true

    private initPos: Vec3 = v3()

    start() {
        input.on(Input.EventType.TOUCH_START, this.onTouchStart, this)
        input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this)
        input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this)
        input.on(Input.EventType.TOUCH_CANCEL, this.onTouchEnd, this)

        this.initPos = this.stickBg.worldPosition.clone()
    }

    update(deltaTime: number) {
        
    }

    private onTouchStart(event: EventTouch) {
        const { x, y } = event.getUILocation()
        if(!this.isFixed) this.stickBg.setWorldPosition(x, y, 0)
    }

    private onTouchMove(event: EventTouch) {
        const { x, y } = event.getUILocation()
        const worldPos = v3(x, y, 0)
        const localPos = v3()

        this.stickBg.inverseTransformPoint(localPos, worldPos)
        const len = localPos.length()
        localPos.normalize()
        localPos.multiplyScalar(math.clamp(len, 0, this.radius))
        this.thumbnail.node.setPosition(localPos)

        VirtualInput.horizontal = this.thumbnail.node.position.x / this.radius
        VirtualInput.vertical = this.thumbnail.node.position.y / this.radius
    }

    private onTouchEnd() {
        this.stickBg.setWorldPosition(this.initPos)
        this.thumbnail.node.setPosition(Vec3.ZERO)

        VirtualInput.horizontal = 0
        VirtualInput.vertical = 0
    }

}


